package com.yntx.usercenter.authentication.service.impl;

import com.yntx.usercenter.authentication.service.OtpService;
import com.yntx.usercenter.authentication.vo.OtpQrCodeVo;
import com.yntx.usercenter.authentication.vo.OtpVo;
import com.yntx.usercenter.common.config.TenantUserContextHolder;
import com.yntx.usercenter.common.util.TotpUtils;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

/**
 * otp服务impl
 *
 * @author jielihaofeng
 * @date 2023-04-24 15:04
 */
@Slf4j
@Service
@AllArgsConstructor
public class TotpServiceImpl implements OtpService {

    @Override
    public OtpVo getOtp(String otpSecret) {
        String otp = TotpUtils.generateTOTP(otpSecret);
        int remainingSeconds = TotpUtils.getRemainingSeconds();
        return OtpVo.builder().otp(otp).remainSeconds(remainingSeconds).build();
    }

    @Override
    public OtpQrCodeVo getOtpQrCode(String username, String otpSecret) {
        if (StringUtils.isEmpty(otpSecret)) {
            throw new IllegalArgumentException("otpSecret不能为空");
        }
        String tenantId = TenantUserContextHolder.get().getTenantId();
        String usernameNotEmpty = StringUtils.defaultIfEmpty(TenantUserContextHolder.get().getUsername(), username);
        String qrCodeStr = TotpUtils.getQrCodeStr(usernameNotEmpty, otpSecret, tenantId);
        log.info("#getOtpQrCode# username:{}, qrCodeStr:{}", usernameNotEmpty, qrCodeStr);
        return OtpQrCodeVo.builder().otpQrCode(qrCodeStr).build();
    }

}
